package com.test;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author mucd
 * 2021年06月09日  下午 03:07
 */

@WebServlet("/download")
public class Download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String path = getServletContext().getRealPath("img/1.avi");
        //serEncode
        encode(resp, path);
        FileInputStream fs = new FileInputStream(path);
        byte[] bytes = new byte[1024];
        int len;
        ServletOutputStream os = resp.getOutputStream();
        while ((len = fs.read(bytes)) != -1){
            os.write(bytes,0,len);
        }
        os.close();
        fs.close();
    }

    /**
     * 传入 response and path
     *
     * @param response
     * @param path
     */
    public static void encode(HttpServletResponse response, String path) {
        try {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(path.substring(path.lastIndexOf("\\") + 1), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
